import 'package:flutter/material.dart';
import 'package:kq_flutter_widgets/resources/l10n/kq_intl.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_widgets/theme/kq_theme_manager.dart';

import '../../resources/kq_theme_colors.dart';
import '../searchBar/kq_search_bar.dart';
import 'kq_drop_down_menu.dart';

typedef KqDropdownItemBuilder = Widget Function(
  BuildContext context,
  int index,
  int count,
  KqDropMenuData data,
  bool isSelected,
);

/// 可搜索的列表控件
/// 主要用于自定义带搜索的下拉，可配合[KqHeaderWithDropdown]一起使用
/// @author 周卓
class KqSearchableDropdownList extends StatefulWidget {
  /// 数据源
  final List<KqDropMenuData> dataList;

  /// 行点击
  final void Function(KqDropMenuData data) onItemTap;

  /// 行渲染
  final KqDropdownItemBuilder itemBuilder;

  /// 每行高度
  final double itemHeight;

  /// 最大可见行数，超过则滚动，默认6行
  final int maxVisibleCount;

  /// 是否启用搜索
  final bool enableSearch;

  /// 自定义空布局
  final Widget? emptyWidget;

  /// 外部传入的异步搜索函数
  final Future<List<KqDropMenuData>> Function(String query)? asyncSearch;

  const KqSearchableDropdownList({
    super.key,
    required this.dataList,
    required this.onItemTap,
    required this.itemBuilder,
    required this.itemHeight,
    this.enableSearch = true,
    this.maxVisibleCount = 6,
    this.emptyWidget,
    this.asyncSearch, // 异步搜索函数
  });

  @override
  State<KqSearchableDropdownList> createState() =>
      _KqSearchableDropdownListState();
}

class _KqSearchableDropdownListState extends State<KqSearchableDropdownList> {
  late List<KqDropMenuData> _filteredList;
  late TextEditingController _controller;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
    _filteredList = List.from(widget.dataList);
  }

  @override
  void didUpdateWidget(covariant KqSearchableDropdownList oldWidget) {
    if (widget.dataList != oldWidget.dataList) {
      _filteredList = List.from(widget.dataList);
    }
    super.didUpdateWidget(oldWidget);
  }

  void _onSearchChanged() {
    final query = _controller.text.trim().toLowerCase();

    if (widget.asyncSearch != null) {
      _performAsyncSearch(query);
    } else {
      _performLocalSearch(query);
    }
  }

  void _performLocalSearch(String query) {
    setState(() {
      if (query.isEmpty) {
        _filteredList = List.from(widget.dataList);
      } else {
        _filteredList = widget.dataList
            .where((item) => item.title.toLowerCase().contains(query))
            .toList();
      }
    });
  }

  void _performAsyncSearch(String query) async {
    setState(() {
      _isLoading = true;
    });

    try {
      final result = await widget.asyncSearch!(query);
      setState(() {
        _filteredList = result;
      });
    } catch (e) {
      setState(() {
        _filteredList = [];
      });
      // 可添加错误处理
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final int itemCount = _filteredList.length;
    final double listHeight = itemCount > widget.maxVisibleCount
        ? widget.itemHeight * widget.maxVisibleCount
        : widget.itemHeight * itemCount;

    return Container(
      color: Colors.white,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (widget.enableSearch)
            KqSearchBar(
              editController: _controller,
              customLeftIcon: _isLoading
                  ? SizedBox(
                      width: 16.r,
                      height: 16.r,
                      child: CircularProgressIndicator(
                        strokeWidth: 2.r,
                        color: KqThemeManager.getCommonConfig().mainColor,
                      ))
                  : null,
              onCancel: () {
                _onSearchChanged();
              },
              onChanged: (value) {
                if (widget.asyncSearch == null) {
                  _onSearchChanged();
                }
              },
              onMonitor: (str) {
                if (widget.asyncSearch != null) {
                  _onSearchChanged();
                }
              },
            ),
          if (_filteredList.isEmpty)
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.r, vertical: 12.r),
              child: widget.emptyWidget ??
                  Row(
                    children: [
                      Text(
                        KqIntl.currentResource.noDataTip,
                        style: TextStyle(
                            fontSize: 14.sp, color: KqThemeColors.text8C),
                      ),
                    ],
                  ),
            )
          else
            SizedBox(
              height: listHeight,
              child: ListView.builder(
                itemCount: _filteredList.length,
                padding: EdgeInsets.zero,
                itemBuilder: (context, index) {
                  final data = _filteredList[index];
                  return GestureDetector(
                    onTap: () => widget.onItemTap(data),
                    child: widget.itemBuilder(context, index,
                        _filteredList.length, data, data.selected),
                  );
                },
              ),
            ),
        ],
      ),
    );
  }
}
